package com.admin.common.controller;


import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.admin.common.constant.Constants;
import com.admin.common.core.controller.BaseController;
import com.admin.common.core.domain.R;
import com.admin.common.exception.ServiceException;
import com.admin.common.utils.DateUtils;
import com.admin.common.utils.StringUtils;
import com.admin.common.utils.file.FileUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * 文件上传 控制层
 *
 * @author Lion Li
 */
@Slf4j
@SaIgnore
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/oss")
public class OssController extends BaseController {

    /**
     * 上传
     *
     * @param file 文件
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<Map<String, String>> upload(@RequestParam(value = "prefix", required = false, defaultValue = "temp") String prefix,
                            @RequestPart("file") MultipartFile file) {
        if (ObjectUtil.isNull(file)) {
            return R.fail("上传文件不能为空");
        }
        String originalFileName = file.getOriginalFilename();
        String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf(".") + 1, originalFileName.length());
        String path = getPath(prefix, suffix);
        File newFile = new File(Constants.UPLOADED_FOLDER  + path);
        newFile.getParentFile().mkdirs();
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            log.error("上传失败:", e);
            throw new ServiceException("上传失败");
        }
        Map<String, String> result = new HashMap();
        result.put("path", path);
        return R.ok(result);
    }

    /**
     * 下载
     *
     * @param path
     * @param response
     * @throws IOException
     */
    @GetMapping("/download/{path}")
    public void download(@PathVariable String path, HttpServletResponse response) throws IOException {
        FileUtils.setAttachmentResponseHeader(response, path.substring(path.lastIndexOf("/") + 1));
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE + "; charset=UTF-8");
        try (InputStream inputStream = new FileInputStream(Constants.UPLOADED_FOLDER + path)) {
            int available = inputStream.available();
            IoUtil.copy(inputStream, response.getOutputStream(), available);
            response.setContentLength(available);
        } catch (Exception e) {
            throw new ServiceException(e.getMessage());
        }
    }

    private String getPath(String prefix, String suffix) {
        // 生成uuid
        String uuid = IdUtil.fastSimpleUUID();
        // 文件路径
        String path = DateUtils.datePath("yyyyMMdd") + "/" + uuid;
        if (StringUtils.isNotBlank(prefix)) {
            path = prefix + "/" + path;
        }
        return "/" + path + "." + suffix;
    }

}
